package com.iie.bigVideo.service.impl;

import com.iie.bigVideo.entity.*;
import com.iie.bigVideo.entity.dto.AnnexDto;
import com.iie.bigVideo.entity.dto.CatalogDto;
import com.iie.bigVideo.entity.dto.UserDto;
import com.iie.bigVideo.mapper.*;
import com.iie.bigVideo.service.CatalogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iie.bigVideo.utils.PageUtils;
import com.iie.bigVideo.utils.ResultUtils;
import com.iie.bigVideo.utils.UUIDUtils;
import com.iie.bigVideo.vo.ResultVO;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author XXX
 * @since 2023-11-24
 */
@Service
public class CatalogServiceImpl extends ServiceImpl<CatalogMapper, Catalog> implements CatalogService {
    @Value("${file.uploadFile}")
    private String uploadFile;
    @Value("${file.uploadFolderMysql}")
    private String uploadFolderMysql; //给数据库存的路径
    @Value("${file.uploadImage}")
    private String uploadImage; // 实际存储图片路径
    @Value("${server.port}")
    private String POST; //获取主机端口
    @Value("${file.uploadFolder}")
    private String uploadFolder; // 静态资源实际存储路径
    @Value("${file.uploadVideo}")
    private String uploadVideo; // 实际存储视频路径

    @Autowired
    private CatalogMapper catalogMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserCatalogMapper userCatalogMapper;
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private AnnexImgMapper annexImgMapper;

    /**
     * 查询目录 和 册
     *
     * @param
     * @return
     */
    @Override
    public ResultVO<List<CatalogDto>> queryCatalog() {
        List<CatalogDto> catalogDto = catalogMapper.queryCatalog();
        if (catalogDto == null) {
            return ResultUtils.error(201, "false", "无数据！");
        }
        return ResultUtils.success(catalogDto);
    }

    /**
     * 查询目录 和 册 和 视频
     *
     * @return
     */
    @Override
    public ResultVO queryCatalogList(int current, int size) {
        if (current <= 0 || size <= 0) {
            return ResultUtils.error(400, "false", "无效参数：current 和 size 必须大于 0");
        }
        Integer count = catalogMapper.countCatalog();//查询目录个数
        if (count == null || count == 0) {
            return ResultUtils.success(null); // 如果没有记录，则无需查询
        }
        // 计算总页数
        int pageCount = (int) Math.ceil((double) count / size);
        // 计算当前页的起始索引
        int start = (current - 1) * size;

        List<CatalogDto> catalogDtoList = catalogDtoListObj(catalogMapper.queryCatalogList(start, size));
        if (catalogDtoList == null) {
            return ResultUtils.error(201, "false", "无数据！");
        }
        // 创建并填充 PageUtils 对象
        PageUtils<CatalogDto> userPageUtils = new PageUtils<>();
        userPageUtils.setCount(count);
        userPageUtils.setPageCount(pageCount);
        userPageUtils.setList(catalogDtoList);
        return ResultUtils.success(userPageUtils);
    }

    /**
     * 添加目录 和 册
     *
     * @param catalog
     * @return
     */
    @Override
    public ResultVO addCatalogDirectory(Catalog catalog, MultipartFile imgFile) {
        if (catalog == null) {
            return ResultUtils.error(500, "false", "服务器异常！");
        }
        Integer last = catalog.getCatalogLast() == null ? 0 : catalog.getCatalogLast();
        catalog.setCatalogLast(last);//上一级
        catalog.setCatalogIsDeleted(0);
        catalog.setCatalogCreatedTime(new Date());
        catalog.setCatalogUpdatedTime(new Date());
        if (imgFile != null && !imgFile.isEmpty() && catalog.getCatalogLast() != null && catalog.getCatalogLast() > 0) {
            //说明有值 是二级的
            String uploadImgFile = uploadFile(imgFile);
            catalog.setCatalogImg(uploadFolderMysql + uploadImage + uploadImgFile);
        }
        catalogMapper.addCatalogDirectory(catalog);
        Catalog catalogObject = catalogMapper.queryAloneByCatalogId(Integer.toString(catalog.getCatalogId()));
        if (catalogObject == null) {
            return ResultUtils.error(201, "false", "添加失败！");
        }
        return ResultUtils.success(catalogObject);
    }

    /**
     * 修改目录 和 册
     *
     * @param catalog
     * @return
     */
    @Override
    public ResultVO updateCatalog(Catalog catalog, MultipartFile imgFile) {
        if (catalog == null) {
            return ResultUtils.error(500, "false", "服务器异常！");
        }
        Catalog catalogObj = catalogMapper.queryAloneByCatalogId(String.valueOf(catalog.getCatalogId()));
        Integer last = catalog.getCatalogLast() == null ? 0 : catalog.getCatalogLast();
        catalog.setCatalogLast(last);//上一级
        catalog.setCatalogUpdatedTime(new Date());
        if (imgFile != null && !imgFile.isEmpty() && catalogObj.getCatalogLast() != null && catalogObj.getCatalogLast() > 0) {
            //说明有值 是二级的
            String uploadImgFile = uploadFile(imgFile);
            //物理删除图片
            deleteFile(uploadFile + catalogObj.getCatalogImg());
            catalog.setCatalogImg(uploadFolderMysql + uploadImage + uploadImgFile);
        }
        Boolean aBoolean = catalogMapper.updateCatalog(catalog);
        return ResultUtils.success(aBoolean);
    }

    /**
     * 删除目录/册
     * 删除目录，就把这个目录下的册也都删除
     *
     * @param catalogId
     * @return
     */
    @Override
    public ResultVO deleteCatalog(int catalogId) {
        // 1. 获取目录对象

        Catalog catalogObject = catalogMapper.queryAloneByCatalogId(String.valueOf(catalogId));
        if (catalogObject == null) {
            return ResultUtils.error(201, "false", "指定的目录或册不存在！");
        }
        // 2. 检查目录类型（0 表示目录，非 0 表示册）
        Integer catalogLast = catalogObject.getCatalogLast();
        if (catalogLast == 0) {
            // 说明是目录
            // 开始查询此目录下的册和册下的视频
            String volumeId = catalogMapper.queryCatalogByCatalogId(catalogId);
            if (!StringUtils.isNotBlank(volumeId)) {
                //单独删目录
                catalogMapper.deleteCatalogList(String.valueOf(catalogId));
            } else {
                // 删除目录和目录下的册
                catalogMapper.deleteCatalogList(volumeId + "," + catalogId);
                //删除图片
                HashMap<String, String> videoId = catalogMapper.queryCatalogByCatalogIdVideo(volumeId);
                if (videoId != null) {
                    if (!videoId.isEmpty()) {
                        deleteVideoWithImgFile(videoId);//删除视频 和 图片
                    }
                }
            }
            deleteUserCatalogId(String.valueOf(catalogId));//删除用户绑定的目录id
            return ResultUtils.success("删除目录成功！");
        } else {
            // 说明是册
            // 开始查询此册下的视频
            HashMap<String, String> videoId = catalogMapper.queryCatalogByCatalogIdVideo(String.valueOf(catalogId));
            if (videoId != null) {
                if (!videoId.isEmpty()) {
                    deleteVideoWithImgFile(videoId);//删除视频 和 图片
                }
            }
            // 删除册
            catalogMapper.deleteCatalogList(Integer.toString(catalogId));
            //物理删除册图片
            deleteFile(uploadFile + catalogObject.getCatalogImg());
            return ResultUtils.success("删除册成功！");
        }
    }

    /**
     * 删除视频 和 图片
     *
     * @param videoId
     */
    public void deleteVideoWithImgFile(HashMap<String, String> videoId) {
        if (videoId.isEmpty()) {
            return;
        }
        // 删除册下有的视频
        catalogMapper.deleteVideoList(videoId.get("videoObjectList_id"));
        // 删除视频和图片文件
        deleteFiles(videoId.get("videoObjectList_url"));
        deleteFiles(videoId.get("videoObjectList_img"));
    }

    private void deleteFiles(String fileUrls) {
        if (fileUrls.isEmpty()) {
            return;
        }

        String[] urls = fileUrls.split(",");
        for (String url : urls) {
            if (!VideoServiceImpl.deleteFile(uploadFile + url)) {
                continue;  //如果没有，就执行下次循环
            }
        }
    }

    /**
     * 删除 普通用户绑定的目录ID
     *
     * @param catalogId
     */
    public void deleteUserCatalogId(String catalogId) {
        userCatalogMapper.deleteUserCatalogImportantCatalog(catalogId);
//        List<User> userList = userMapper.deleteUserCatalogId(catalogId);
//        if (userList.size() > 0) {
//            for (User user : userList) {
//                String replace = user.getCatalogId().replace(catalogId + ",", "").replace("," + catalogId, "").replace(catalogId, "");
//                user.setCatalogId(replace);//重新赋值
//            }
//            userMapper.updateUserList(userList);//进行批量修改。
//        }
    }

    public String uploadFile(MultipartFile file) {
        //校验上传的 是图片 还是 视频
        String contentType = file.getContentType();
        boolean image = contentType.startsWith("image");//如果是 image 开头 就是 图片
        String originalFilename = file.getOriginalFilename();//原文件名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));//扩展名
        String newFileName = "";
        try {
            if (image) {
                //图片
                //生成新的文件名
                newFileName = UUIDUtils.getUUID(16) + extension;
//                File fileObject = new File(Class.class.getClass().getResource("/").getPath() + uploadFolder + uploadImage);
                File fileObject = new File(uploadFolder + uploadImage);
                if (!fileObject.exists()) {
                    fileObject.mkdirs();//没有就创建
                }
                file.transferTo(new File(fileObject, newFileName));//对文件进行上传
            } else {
                //视频
                //生成新的文件名
                newFileName = UUIDUtils.getUUID(16) + extension;
//                File fileObject = new File(Class.class.getClass().getResource("/").getPath() + uploadFolder + uploadVideo);
                File fileObject = new File(uploadFolder + uploadVideo);
                if (!fileObject.exists()) {
                    fileObject.mkdirs();//没有就创建
                }
                file.transferTo(new File(fileObject, newFileName));//对文件进行上传
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return newFileName;
    }

    /**
     * 删除文件
     *
     * @return
     */
    public static Boolean deleteFile(String filePath) {
        File dir = new File(filePath);
        //isFile()判断是否是文件，exists()判断该文件是否存在，delete()删除成功返回1失败则返回0
        if (dir.isFile() && dir.exists() && dir.delete()) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 处理返回结果
     *
     * @return
     */
    private List<CatalogDto> catalogDtoListObj(List<CatalogDto> catalogList) {
        if (catalogList.size() > 0) {
            //册
            for (CatalogDto catalogDto : catalogList) {
                if (catalogDto.getCatalogList().size() > 0) {
                    //课件
                    for (CatalogDto dto : catalogDto.getCatalogList()) {
                        if (dto.getAnnexList().size() > 0) {
                            //附件
                            for (AnnexDto annex : dto.getAnnexList()) {
                                ArrayList<String> imageId = new ArrayList<>();
                                //图集
                                imageId.add(Integer.toString(annex.getId()));
                                if (imageId.size() > 0) {
                                    ArrayList<Image> imageArrayList = new ArrayList<>();
                                    //有图集
                                    List<Image> imageList = annexImgMapper.queryByAnnexIdList(imageId);
                                    if (!imageList.isEmpty()) {
                                        for (Image image : imageList) {
                                            if (StringUtils.isNotBlank(image.getImageMainImg())) {
                                                //有封面
                                                imageArrayList.add(image);
                                            }
                                            imageArrayList.add(image);
                                        }
                                    }
                                    annex.setImageList(imageArrayList);
                                }
                            }


                        }
                    }
                }

            }
        }
        return catalogList;
    }
}
